const { findLoanListByName, findLoanList, getLoanCountByName, getLoanCount, 
  insertLoan, updateLoanSqlFun, deleteLoanSqlFun } = require("../model/loan");
const { mkPager, checkNullValue } = require("../utils");

exports.loanList = async ctx => {
  const { pageNo, pageSize, name } = ctx.query;

  const { limitA, limitB } = mkPager(pageNo, pageSize);
  console.log(limitA, limitB);
  if (name) {
    var dataRes = await findLoanListByName(name, limitA, limitB)
    var countRes = await getLoanCountByName(name)
  } else {
    var dataRes = await findLoanList(limitA, limitB)
    var countRes = await getLoanCount()
  }
  if (!dataRes.length) return ctx.faild({ msg: '查询异常，请稍后重试' })

  const { total } = countRes[0]
  const page = Math.ceil(total / pageSize)
  ctx.success({
    msg: '查询成功',
    result: dataRes,
    total,  // 总条数
    page,   // 有多少页
    pageSize  // 每页大小
  })
}

// 创建贷款申请
exports.creatLoanItem = async ctx => {
  const o = ctx.request.body;
  const res = checkNullValue(o, checkList)
  if (!res.result) return ctx.faild({ msg: `字段【${res.key}】缺失，值为${res.value}` })

  const insertRes = await insertLoan(o)

  if (insertRes.affectedRows != 1) return ctx.faild({ msg: '添加失败' })

  ctx.success({ msg: '操作成功' })
}

// 更新
exports.updateLoanItem = async ctx => {
  // 
  const { type } = ctx.state.user;
  if (type != ADMIN && type != INPUT) return ctx.faild({ msg: '无更新权限' })

  let reqData = ctx.request.body;
  const id = reqData.id

  const updateRes = await updateLoanSqlFun(reqData, id)
  if (updateRes.changedRows != 1) return ctx.faild({ msg: '更新失败' })

  ctx.success({ msg: '操作成功' })
}

// 删除
exports.deleteLoan = async ctx => {
  // 权限验证
  const { type } = ctx.state.user;
  if (type != ADMIN && type != INPUT) return ctx.faild({ msg: '无删除权限' })

  // ctx.pqrams 可以取到路由动态传参
  const id = ctx.params.delId

  const deleteRes = await deleteLoanSqlFun(id)
  if (deleteRes.affectedRows != 1) return ctx.faild({ msg: '删除失败' })

  ctx.success({ msg: '操作成功' })
}